package utilities;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import utilDataStruct.FileStruct;

public class FinalHandler {

	public static void FinishCode(String tFolder, String frameFolder,
			Map<String, String> nameToType, List<FileStruct> fileList, int ruleNum) {

		StringBuilder sb = new StringBuilder();
		Set<String> keys = nameToType.keySet();
		for (Iterator<String> it = keys.iterator(); it.hasNext();) {
            String s = (String)it.next();
            sb.append("\t\tglobalConf.set(\"" + s + "\", \"" + nameToType.get(s) + "\");\n");
        }
		
		StringBuilder sb1 = new StringBuilder();
		sb1.append("\t\tString tableNames = \"" + fileList.get(0).getTableName());
		for (int ww=1; ww<fileList.size(); ww++) {
			sb1.append(" " + fileList.get(ww).getTableName());
		}
		sb1.append("\";");
		
		BufferedReader br_Profile, br_import, br;
		BufferedWriter bw;
		try {
			br_Profile = new BufferedReader(new FileReader(tFolder + "/tempProfile"));
			br_import = new BufferedReader(new FileReader(tFolder + "/tempImport"));
			br = new BufferedReader(new FileReader(frameFolder + "ImportT"));
			bw = new BufferedWriter(new FileWriter(tFolder + "/MapReduceTest.java"));
			String line, lineInsert;
			String[] strArray;
			
			while ((line=br.readLine()) != null) {
				if (line.equals("#2#")) {
					while ((lineInsert=br_Profile.readLine()) != null) {
						bw.write(lineInsert + "\n");
						bw.flush();
					}
					bw.write("\n");
					bw.flush();
				} else if (line.equals("#1#")) {
					bw.write(sb.toString());
					bw.write("\n");
					bw.flush();
				} else if (line.equals("#3#")) {
					bw.write(sb1.toString());
					bw.write("\n");
					bw.flush();
				} else if (line.equals("#5#")) {
					while ((lineInsert=br_import.readLine()) != null) {
						bw.write(lineInsert + "\n");
						bw.flush();
					}
				} else {
					strArray = line.split("#");
					if (strArray.length > 1) {
						if (strArray[1].equals("0")) {
							String[] pathFolder = tFolder.split("/");
							strArray[1] = pathFolder[pathFolder.length - 1];
							line = strArray[0] + strArray[1] + strArray[2];
						} else if (strArray[1].equals("4")) {
							strArray[1] = ruleNum + "";
							line = strArray[0] + strArray[1] + strArray[2];
						}
					}
					bw.write(line + "\n");
					bw.flush();
				} // if_else
			} // while
			
			br.close();
			br_Profile.close();
			bw.close();
			
			File f = new File(tFolder + "/tempProfile");
			f.delete();
			f = new File(tFolder + "/tempImport");
			f.delete();
		} catch (IOException ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		} finally {
			bw = null;
			br = null;
			br_Profile = null;
		}
	}

}
